{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WZ1G8QHhdHZR"
   },
   "source": [
    "##### Copyright 2020 The Cirq Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "KQa9t_gadIuR"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xwec7FrkdFmi"
   },
   "source": [
    "# Gates and operations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5KZia7jmdJ3V"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.example.org/cirq/gates\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on QuantumLib</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/gates.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/gates.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/gates.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bd9529db1c0b"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import cirq\n",
    "except ImportError:\n",
    "    print(\"installing cirq...\")\n",
    "    !pip install --quiet cirq\n",
    "    print(\"installed cirq.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "y8P1T6duC-yo"
   },
   "source": [
    "A `Gate` is an effect that can be applied to a collection of\n",
    "qubits (objects with a ``Qid``).  `Gates` can be applied\n",
    "to qubits by calling their ``on`` method, or, alternatively\n",
    "calling the gate on the qubits.  The object created by such calls\n",
    "is an ``Operation``.  Alternatively, a `Gate` can be thought of\n",
    "as a [factory](https://en.wikipedia.org/wiki/Factory_method_pattern) \n",
    "that, given input qubits, generates an associated\n",
    "`GateOperation` object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-Gbg8dEJDH4D"
   },
   "source": [
    "## Gates versus operations\n",
    "\n",
    "![Circuits and Moments](images/moments.png)\n",
    "\n",
    "The above example shows the first half of a quantum teleportation circuit,\n",
    "found in many quantum computation textbooks.  This example uses three different\n",
    "gates: a Hadamard (H), controlled-Not (CNOT), and measurement.  These are\n",
    "represented in cirq by ```cirq.H```, ```cirq.CNOT```, and ``cirq.measure``,\n",
    "respectively.\n",
    "\n",
    "In this example, a Hadamard is an example of a `Gate` object that can be applied\n",
    "in many different circumstances and to many different qubits.  Note that the\n",
    "above example has two instances of an H gate but applied to different qubits.\n",
    "This is an example of one `Gate` type with two `Operation` instances, one\n",
    "applied to the qubit '|b⟩' and the other applied to qubit '|a⟩'.\n",
    "\n",
    "Gates can generally be applied to any type of qubit (``NamedQubit``,\n",
    "``LineQubit``, ``GridQubit``, etc. - see [Qubits](qubits.ipynb) for more details) to create an Operation. \n",
    "\n",
    "The following example shows how to construct each of these gates and operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "psYGZcjUEF5V"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "H(b)\n",
      "CNOT(b, c)\n",
      "CNOT(a, b)\n",
      "H(a)\n",
      "cirq.MeasurementGate(2, 'a,b', ())(a, b)\n"
     ]
    }
   ],
   "source": [
    "import cirq\n",
    "\n",
    "# This examples uses named qubits to remain abstract.\n",
    "# However, we can also use LineQubits or GridQubits to specify a geometry\n",
    "a = cirq.NamedQubit('a')\n",
    "b = cirq.NamedQubit('b')\n",
    "c = cirq.NamedQubit('c')\n",
    "\n",
    "# Example Operations, that correspond to the moments above\n",
    "print(cirq.H(b))\n",
    "print(cirq.CNOT(b, c))\n",
    "print(cirq.CNOT(a, b))\n",
    "print(cirq.H(a))\n",
    "print(cirq.measure(a,b))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SrBowKP2EQVC"
   },
   "source": [
    "This would create the operations needed to comprise the circuit from the above\n",
    "diagram.  The next step would be composing these operations into moments and\n",
    "circuits.  For more on those types, see the documentation on\n",
    "[Circuits](circuits.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "FGS-owSsESxX"
   },
   "source": [
    "## Other gate features\n",
    "\n",
    "Most ``Gate``s operate on a specific number of qubits, which can be accessed\n",
    "by the ``num_qubits()`` function.  One notable exception is the\n",
    "``MeasurementGate`` which can be applied to a variable number of qubits.\n",
    "\n",
    "Most gates also have a unitary matrix representation, which can be accessed\n",
    "by ``cirq.unitary(gate)``.  \n",
    "\n",
    "Not all `Gate`s correspond to unitary evolution. They may represent a\n",
    "probabilistic mixture of unitaries, or a general quantum channel. The component\n",
    "unitaries and associated probabilities of a mixture can be accessed by\n",
    "`cirq.mixture(gate)`. The Kraus operator representation of a channel can be\n",
    "accessed by `cirq.channel(gate)`. Non-unitary gates are often used in the\n",
    "simulation of noise. See [noise documentation](noise.ipynb) for more details.\n",
    "\n",
    "Many arithmetic operators will work in the expected way when applied to\n",
    "gates.  For instance, ``cirq.X**0.5`` represents a square root of X gate.\n",
    "These can also be applied to Operators for a more compact representation, such\n",
    "as ``cirq.X(q1)**0.5`` will be a square root of X gate applied to the q1\n",
    "qubit.  This functionality depends on the \"magic methods\" of the gate\n",
    "being defined (see below for details).\n",
    "\n",
    "Gates can be converted to a controlled version by using `Gate.controlled()`.\n",
    "In general, this returns an instance of a `ControlledGate`.  However, for\n",
    "certain special cases where the controlled version of the gate is also a\n",
    "known gate, this returns the instance of that gate.\n",
    "For instance, `cirq.X.controlled()` returns a `cirq.CNOT` gate.\n",
    "Operations have similar functionality `Operation.controlled_by()`, such as\n",
    "`cirq.X(q0).controlled_by(q1)`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SvKdNtObE1uG"
   },
   "source": [
    "## Common gates\n",
    "\n",
    "Cirq supports a number of gates natively, with the opportunity to extend these\n",
    "gates for more advanced use cases."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Qrm9v06bFIpq"
   },
   "source": [
    "### Measurement gate\n",
    "\n",
    "**cirq.MeasurementGate** This is a measurement in the computational basis.\n",
    "This gate can be applied to a variable number of qubits.  The function\n",
    "`cirq.measure(q0, q1, ...)` can also be used as a short-hand to create a\n",
    "`MeasurementGate` ."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hN4FVlBvFJyo"
   },
   "source": [
    "### Single qubit gates\n",
    "\n",
    "Most single-qubit gates can be thought of as rotation around an axis in the\n",
    "[Bloch Sphere](https://en.wikipedia.org/wiki/Bloch_sphere) representation and\n",
    "are usually referred to by their axis of rotation.  Some operators use the notation of a 'half-turn' which is defined as a 180 degree (pi radians) rotation around the axis.\n",
    "\n",
    "**cirq.X / cirq.Y / cirq.Z** The [Pauli gates](https://en.wikipedia.org/wiki/Quantum_logic_gate#Pauli-X_gate) X, Y, and Z which rotate the state around the  associated axis by one half-turn.\n",
    "\n",
    "**cirq.rx(rads)** A rotation about the Pauli 'X' axis in terms of radians.  This is equivalent to `exp(-i X rads / 2) = cos(rads/2) I - i sin(rads/2) X`\n",
    "\n",
    "**cirq.ry(rads)** A rotation about the Pauli 'Y' axis in terms of radians.  This is equivalent to `exp(-i Y rads / 2) = cos(rads/2) I - i sin(rads/2) Y`\n",
    "\n",
    "**cirq.rz(rads)** A rotation about the Pauli 'Z' axis in terms of radians.  This is equivalent to `exp(-i Z rads / 2) = cos(rads/2) I - i sin(rads/2) Z`\n",
    "\n",
    "**cirq.XPowGate(exponent=t)** Rotations about the Pauli ``X`` axis, equivalent to ``cirq.X**t``.  See [XPowGate](https://cirq.readthedocs.io/en/latest/generated/cirq.XPowGate.html) for its unitary matrix.  Note that this has a global phase of $e^{i·π·t/2}$ versus the traditionally defined rotation matrix, which can be modified by the optional parameter `global_shift`.\n",
    "\n",
    "**cirq.YPowGate(exponent=t)** Rotations about the Pauli ``Y`` axis, equivalent to ``cirq.Y**t``.  See [YPowGate](https://cirq.readthedocs.io/en/latest/generated/cirq.YPowGate.html) for its unitary matrix.  Note that this has a global phase of $e^{i·π·t/2}$ versus the traditionally defined rotation matrix, which can be modified by the optional parameter `global_shift`.\n",
    "\n",
    "**cirq.ZPowGate(exponent=t)** Rotations about the Pauli ``Z`` axis, equivalent to ``cirq.Z**t``.  See [ZPowGate](https://cirq.readthedocs.io/en/latest/generated/cirq.ZPowGate.html) for its unitary matrix.  Note that this has a global phase of $e^{i·π·t/2}$ versus the traditionally defined rotation matrix, which can be modified by the optional parameter `global_shift`.\n",
    "\n",
    "**cirq.PhasedXPowGate**\n",
    "This gate is a rotation about an axis in the XY plane of the Bloch sphere.\n",
    "The ``PhasedXPowGate`` takes two parameters, ``exponent`` and ``phase_exponent``.\n",
    "The gate is equivalent to the circuit `───Z^-p───X^t───Z^p───` where `p` is the\n",
    "`phase_exponent` and `t` is the `exponent`.\n",
    "\n",
    "**cirq.H / cirq.HPowGate** The Hadamard gate is a rotation around the X+Z axis.\n",
    "`cirq.HPowGate(exponent=t)` is a variable rotation of t turns around this\n",
    "axis. `cirq.H` is a π rotation and is equivalent to\n",
    "`cirq.HPowGate(exponent=1)`\n",
    "\n",
    "**S** The square root of Z gate, equivalent to `cirq.Z**0.5`\n",
    "\n",
    "**T** The fourth root of Z gate, equivalent to `cirq.Z**0.25`.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JERikgqQFNRN"
   },
   "source": [
    "### Two qubit gates\n",
    "\n",
    "**cirq.CZ / cirq.CZPowGate** The controlled-Z gate.  A two qubit gate that\n",
    "phases the |11⟩ state.  `cirq.CZPowGate(exponent=t)` is equivalent to\n",
    "`cirq.CZ**t` and has a matrix representation of ``exp(i pi |11⟩⟨11| t)``.\n",
    "\n",
    "**cirq.CNOT / cirq.CNotPowGate** The controlled-X gate.  This gate swaps the\n",
    "|11⟩ and |10⟩ states.  `cirq.CNotPowGate(exponent=t)` is equivalent\n",
    "to `cirq.CNOT**t` .\n",
    "\n",
    "**cirq.SWAP / cirq.SwapPowGate** The swap gate swaps the |01⟩ and |10⟩ states.\n",
    "`cirq.SWAP**t` is the same as `cirq.SwapPowGate(exponent = t)`\n",
    "\n",
    "**cirq.ISWAP / cirq.ISwapPowGate**  The iSwap gate swaps the |01⟩ and |10⟩\n",
    "states and adds a relative phase of i.  `cirq.ISWAP**t` is the same as\n",
    "`cirq.ISwapPowGate(exponent = t)`\n",
    "\n",
    "**Parity gates**: The gates cirq.XX, cirq.YY, and cirq.ZZ are equivalent to\n",
    "performing the equivalent one-qubit Pauli gates on both qubits.  The gates\n",
    "cirq.XXPowGate, cirq.YYPowGate, and cirq.ZZPowGate are the powers of\n",
    "these gates.  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0orm9plNFR_P"
   },
   "source": [
    "### Other gates\n",
    "\n",
    "**cirq.MatrixGate**: A gate defined by its unitary matrix in the form of a\n",
    "numpy ndarray.\n",
    "\n",
    "**cirq.WaitGate**:  This gate does nothing for a specified `cirq.Duration`\n",
    "amount of time.  This is useful for conducting T1 and T2 decay experiments. \n",
    "\n",
    "**cirq.CCNOT, cirq.CCX, cirq.TOFFOLI, cirq.CCXPowGate**: Three qubit gates\n",
    "representing the controlled-controlled-X gates.\n",
    "\n",
    "**cirq.CCZ, cirq.CCZPowGate**: Three qubit gates representing a\n",
    "controlled-controlled-Z gate.\n",
    "\n",
    "**CSWAP, CSwapGate, FREDKIN**: Three qubit gates representing a controlled-SWAP\n",
    "gate."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QCMQA9PYFWtt"
   },
   "source": [
    "## Advanced: create your own gates\n",
    "\n",
    "If the above gates are not sufficient for your use case, it is fairly simple\n",
    "to create your own gate.   In order to do so, you can define your class and\n",
    "inherit the `cirq.Gate` class and define the functionality in your class.\n",
    "For more information, see [this guide](custom_gates.ipynb)."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "Sh9QBnKbFf_B"
   ],
   "name": "gates.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
